package com.szosen.idcardActivity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.grg.idcard.IDCardMsg;
import com.grg.idcard.IDCardRecognition;
import com.grg.idcard.IDCardRecognition.IDCardRecListener;
import com.szosen.database.DBService;
import com.szosen.database.HealthRecord;
import com.szosen.jkzj.R;
import com.szosen.jkzj.activity.BaseActivity;
import com.szosen.jkzj.activity.JKDAActivity;
import com.szosen.jkzj.util.Contants;
import com.szosen.json.database.ArchiveBean;
import com.szosen.json.database.JSONDBService;
import com.szosen.util.ToastTool;

import java.util.List;

@SuppressLint("NewApi")
public class IDCardActivity extends BaseActivity {

    Dialog dialog;
    private Context mContext;
    private TextView tv_putIdCard;

    /**
     * Called when the activity is first created.
     */
    private IDCardRecognition mIDCardRecognition;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.read_id_card_new);
        mContext = this;
        btconn = (Button) findViewById(R.id.btn_find_id_reader);
        btread = (Button) findViewById(R.id.btnInit);
        btclose = (Button) findViewById(R.id.btn_off);
        image = (ImageView) findViewById(R.id.ivImageview);
        txtInfo = (TextView) findViewById(R.id.tv_info);
        txtDeviceStatus = (TextView) findViewById(R.id.conn_status);
        tv_putIdCard = (TextView) findViewById(R.id.readidcard_tv_putidcard);
        tv_putIdCard.setVisibility(View.VISIBLE);
        // TextView tv_title = (TextView) findViewById(R.id.main_all_tv_title);
        // tv_title.setText("身份证读卡");
        // btclose.setEnabled(false);
        txtInfo.setText("你好");
        image.setVisibility(View.INVISIBLE);
        txtInfo.setVisibility(View.INVISIBLE);
//		txtDeviceStatus.setVisibility(View.INVISIBLE);
        txtDeviceStatus
                .setText(Contants.Bluetooth_connecting.BLUETOOTH_CONNECTING);
        txtDeviceStatus.setTextColor(Color.BLUE);
        btread.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                image.setVisibility(View.INVISIBLE);
                txtInfo.setVisibility(View.INVISIBLE);
                tv_putIdCard.setVisibility(View.VISIBLE);// 只显示放进身份证。。。
//				startReadIdCard();
            }
        });
    }

    public void connnectDeviceAgain(View view) {
        startReadIdCard();
    }

    private void startReadIdCard() {
        if (mIDCardRecognition != null) {
            mIDCardRecognition.close();
        }
        mIDCardRecognition = new IDCardRecognition(IDCardActivity.this,
                mIDCardRecListener);
        mIDCardRecognition.start();
    }

    private IDCardRecListener mIDCardRecListener = new IDCardRecListener() {
        @Override
        public void onResp(IDCardMsg info) {
            if (info == null) {
                // txtInfo.setText("");
                // image.setImageBitmap(null);
                return;
            }
            String text = info.getName() + "\n" + info.getSexStr() + "\n"
                    + info.getNationStr() + "族" + "\n" + info.getBirthDate()
                    + "\n" + info.getIdCardNum() + "\n" + info.getAddress()
                    + "\n" + "有效期：" + info.getUsefulStartDate() + "至"
                    + (info.getUsefulEndDate() == null ? "长期" : info.getUsefulEndDate()) + "\n" + info.getSignOffice()
                    + "\n";
//            System.out.println("读取到的身份证信息："+text);
            // 读取到身份证信息后显示身份证图片和文本信息
            image.setVisibility(View.VISIBLE);
            txtInfo.setVisibility(View.VISIBLE);
            tv_putIdCard.setVisibility(View.INVISIBLE);
            txtInfo.setText(text);
            Bitmap bitmap = BitmapFactory.decodeByteArray(info.getPortrait(),
                    0, info.getPortrait().length);
            image.setImageBitmap(bitmap);
            boolean flag = false;
            //查询用户列表
            JSONDBService dService = JSONDBService.getInstance(context);
            List<Object> list = dService.getAll(new ArchiveBean());
            for (int i = 0; list != null && i < list.size(); i++) {
                ArchiveBean hr = (ArchiveBean) list.get(i);
                String card = hr.getIdcard().trim();
                if (!TextUtils.isEmpty(card)
                        && card.equals(info.getIdCardNum().trim())) {
                    Intent intent = new Intent();
                    intent.putExtra("IdCard", info.getIdCardNum().trim());
                    intent.putExtra("name", info.getName().trim());
                    setResult(0, intent);
                    flag = true;
                    finish();
                }
            }
            if (!flag) {
                Intent intent = new Intent(IDCardActivity.this,
                        JKDAActivity.class);
                intent.putExtra("flag", "addUser");
                intent.putExtra("idCard", info.getIdCardNum());
                intent.putExtra("name", info.getName());
                intent.putExtra("address", info.getAddress());
                intent.putExtra("sex", info.getSexStr());
                intent.putExtra("nation", info.getNationStr());
                startActivity(intent);
                finish();
            }
        }

        @Override
        public void onConnectState(String msg) {
            myReadIdCardHandler.obtainMessage(WHAT_CONNECTSUCCESS)
                    .sendToTarget();
        }
    };

    @SuppressLint("ResourceAsColor")
    @Override
    protected void onResume() {
        super.onResume();
        super.setTitleContent("【身份证刷卡】");
        startReadIdCard();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    private Button btconn;
    private Button btread;
    private ImageView image;
    private Button btclose;
    private TextView txtDeviceStatus;// 读卡器连接状态
    private TextView txtInfo;

    private final static int WHAT_IMAGEVIEW = 111;
    private final static int WHAT_NAME = 222;
    private final static int WHAT_IMAGEDECODEFAILED = 444;
    private final static int WHAT_SHOWDIALOG = 666;
    private final static int WHAT_READIDCARDFAILED = 999;
    private final static int WHAT_READIDCARDERROR = 99999;
    private final static int WHAT_CONNECTERROR = 44444;
    private final static int WHAT_CONNECTSUCCESS = 66666;
    private final static int WHAT_CONNECTHAND = 55555;

    @SuppressWarnings("deprecation")
    @Override
    protected void onDestroy() {
        mIDCardRecognition.close();
        super.onDestroy();
    }

    Handler myReadIdCardHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case WHAT_IMAGEVIEW:
                    // 读取到身份证图片
                    image.setVisibility(View.VISIBLE);
                    tv_putIdCard.setVisibility(View.INVISIBLE);
                    Bitmap bmp = (Bitmap) msg.obj;
                    image.setImageBitmap(bmp);
                    break;
                case WHAT_NAME:
                    // 读取到身份证名字
                    // tv.setVisibility(View.VISIBLE);
                    txtInfo.setVisibility(View.VISIBLE);
                    tv_putIdCard.setVisibility(View.INVISIBLE);
                    String s = (String) msg.obj;
                    txtInfo.setText("您好, " + s);
                    List<Object> list = DBService.getInstance(context).getAll(
                            new HealthRecord());
                    boolean flag = false;
                    for (int i = 0; i < list.size(); i++) {
                        HealthRecord hr = (HealthRecord) list.get(i);
                        String card = hr.getIdCard().trim();
                        if (!TextUtils.isEmpty(card)) {
                            Intent intent = new Intent();
                            System.out.println("进入到原来的列表");
                            setResult(0, intent);
                            flag = true;
                            finish();
                        }
                    }
                    if (!flag) {
                        Intent intent = new Intent(IDCardActivity.this,
                                JKDAActivity.class);
                        // intent.putExtra("flag", "addUser");
                        // intent.putExtra("idCard", mIdCardMsg.id_num);
                        // intent.putExtra("name", mIdCardMsg.name);
                        // intent.putExtra("address", mIdCardMsg.address);
                        // intent.putExtra("sex", mIdCardMsg.sex);
                        // intent.putExtra("nation", mIdCardMsg.nation_str);
                        startActivity(intent);
                        finish();
                    }
                    break;
                case WHAT_IMAGEDECODEFAILED:
                    ToastTool.showShort(
                            mContext,
                            "照片解码失败，请检查路径"
                                    + Environment.getExternalStorageDirectory()
                                    + "/wltlib/");
                    image.setImageBitmap(BitmapFactory.decodeResource(
                            getResources(), R.drawable.face));
                    image.setVisibility(View.INVISIBLE);
                    // tv.setVisibility(View.INVISIBLE);
                    break;
                case WHAT_CONNECTHAND:
                    image.setVisibility(View.INVISIBLE);
                    txtInfo.setVisibility(View.INVISIBLE);
                    tv_putIdCard.setVisibility(View.INVISIBLE);
                    break;
                case WHAT_SHOWDIALOG:
                    // mReadIdCardFlag = false;
                    tv_putIdCard.setVisibility(View.INVISIBLE);
                    break;
                case WHAT_READIDCARDFAILED:
                    tv_putIdCard.setVisibility(View.VISIBLE);
                    break;
                case WHAT_READIDCARDERROR:
                    // ToastTool.showShort(mContext, "");
                    txtDeviceStatus
                            .setText(Contants.Bluetooth_connecting.BLUETOOTH_CONNECT_NULL);
                    txtDeviceStatus.setTextColor(Color.RED);
                    break;
                case WHAT_CONNECTSUCCESS:
                    tv_putIdCard.setVisibility(View.VISIBLE);// 设备连接成功后显示放进身份证。。。
                    txtDeviceStatus
                            .setText(Contants.Bluetooth_connecting.BLUETOOTH_CONNECTSUCCESS);
                    txtDeviceStatus.setTextColor(Color.BLUE);
                    break;
                case WHAT_CONNECTERROR:
                    // ToastTool.showShort(mContext, "设备连接失败");
                    txtDeviceStatus
                            .setText(Contants.Bluetooth_connecting.BLUETOOTH_CONNECTFAILED);
                    txtDeviceStatus.setTextColor(Color.RED);
                    break;
                default:
                    break;
            }
        }

        ;
    };

    private String decodeNation(int code) {
        String nation;
        switch (code) {
            case 1:
                nation = "汉";
                break;
            case 2:
                nation = "蒙古";
                break;
            case 3:
                nation = "回";
                break;
            case 4:
                nation = "藏";
                break;
            case 5:
                nation = "维吾尔";
                break;
            case 6:
                nation = "苗";
                break;
            case 7:
                nation = "彝";
                break;
            case 8:
                nation = "壮";
                break;
            case 9:
                nation = "布依";
                break;
            case 10:
                nation = "朝鲜";
                break;
            case 11:
                nation = "满";
                break;
            case 12:
                nation = "侗";
                break;
            case 13:
                nation = "瑶";
                break;
            case 14:
                nation = "白";
                break;
            case 15:
                nation = "土家";
                break;
            case 16:
                nation = "哈尼";
                break;
            case 17:
                nation = "哈萨克";
                break;
            case 18:
                nation = "傣";
                break;
            case 19:
                nation = "黎";
                break;
            case 20:
                nation = "傈僳";
                break;
            case 21:
                nation = "佤";
                break;
            case 22:
                nation = "畲";
                break;
            case 23:
                nation = "高山";
                break;
            case 24:
                nation = "拉祜";
                break;
            case 25:
                nation = "水";
                break;
            case 26:
                nation = "东乡";
                break;
            case 27:
                nation = "纳西";
                break;
            case 28:
                nation = "景颇";
                break;
            case 29:
                nation = "柯尔克孜";
                break;
            case 30:
                nation = "土";
                break;
            case 31:
                nation = "达斡尔";
                break;
            case 32:
                nation = "仫佬";
                break;
            case 33:
                nation = "羌";
                break;
            case 34:
                nation = "布朗";
                break;
            case 35:
                nation = "撒拉";
                break;
            case 36:
                nation = "毛南";
                break;
            case 37:
                nation = "仡佬";
                break;
            case 38:
                nation = "锡伯";
                break;
            case 39:
                nation = "阿昌";
                break;
            case 40:
                nation = "普米";
                break;
            case 41:
                nation = "塔吉克";
                break;
            case 42:
                nation = "怒";
                break;
            case 43:
                nation = "乌孜别克";
                break;
            case 44:
                nation = "俄罗斯";
                break;
            case 45:
                nation = "鄂温克";
                break;
            case 46:
                nation = "德昂";
                break;
            case 47:
                nation = "保安";
                break;
            case 48:
                nation = "裕固";
                break;
            case 49:
                nation = "京";
                break;
            case 50:
                nation = "塔塔尔";
                break;
            case 51:
                nation = "独龙";
                break;
            case 52:
                nation = "鄂伦春";
                break;
            case 53:
                nation = "赫哲";
                break;
            case 54:
                nation = "门巴";
                break;
            case 55:
                nation = "珞巴";
                break;
            case 56:
                nation = "基诺";
                break;
            case 97:
                nation = "其他";
                break;
            case 98:
                nation = "外国血统中国籍人士";
                break;
            default:
                nation = "";
                break;
        }
        return nation;
    }

    Bitmap bmp(Bitmap bp) {
        float scaleWidth = 1;
        float scaleHeight = 1;
        int bmpWidth = bp.getWidth();
        int bmpHeight = bp.getHeight();
        /* 设置图片放大的比例 */
        double scale = 2;
        /* 计算这次要放大的比例 */
        scaleWidth = (float) (scaleWidth * scale);
        scaleHeight = (float) (scaleHeight * scale);

		/* 产生reSize后的Bitmap对象 */
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap resizeBmp = Bitmap.createBitmap(bp, 0, 0, bmpWidth, bmpHeight,
                matrix, true);
        return resizeBmp;
    }

}

class IdCardMsg {
    public String name;
    public String sex;
    public String nation_str;

    public String birth_year;
    public String birth_month;
    public String birth_day;
    public String address;
    public String id_num;
    public String sign_office;

    public String useful_s_date_year;
    public String useful_s_date_month;
    public String useful_s_date_day;

    public String useful_e_date_year;
    public String useful_e_date_month;
    public String useful_e_date_day;
    public byte[] photo;

}